package util

import "math/rand"

//
//NOTE 通常场景下，用之前需要先设置随机数种子
//如果权重是0，除非是唯一元素，否则不会被随机到
func RandomIndexByWeights(weights []int) int {
	if len(weights) == 0 {
		return -1
	}

	if len(weights) == 1 {
		return 0
	}

	var total int
	for _, w := range weights {
		total += w
	}

	r := rand.Intn(total)

	for i, w := range weights {
		r -= w
		if r < 0 {
			return i
		}
	}

	return -2
}
